package paperToChaKanChengJi

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.listener.OnChartValueSelectedListener
import com.lancoo.cpbase.authentication.base.CurrentUser
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.bindLifeCycle
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.MarkViewModel
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToEvaluation.AibkPaperEvaluationActivity
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.AibkAnalysisAnswerSheetActivity
import com.lancoo.znbkxx.teacher.base.BaseVMActivity
import com.lancoo.znbkxx.teacher.databinding.ActivityCheckScoreBinding
import com.lancoo.znbkxx.teacher.ui.Presenter
import com.lancoo.znbkxx.teacher.utils.ExportUtil
import org.koin.androidx.viewmodel.ext.android.viewModel
import paperToChaKanChengJi.adapter.AnalysisAdapter
import paperToChaKanChengJi.adapter.SubjectAdapter
import paperToChaKanChengJi.data.StuScore
import paperToChaKanChengJi.data.TypeScoreRate
import paperToChaKanChengJi.dialog.ExportTestPaperDialog
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

/**
 * Created by Dadong on 2020/3/19
 * Describe: 查看成绩界面
 */
class CheckScoreActivity : BaseVMActivity<CheckScoreViewModel, ActivityCheckScoreBinding>(), Presenter, BaseQuickAdapter.OnItemClickListener {
    private var setId = ""
    private var paperId = ""
    private var layer = 0
    private var paperName = ""
    private lateinit var state: ArrayList<String>
    private lateinit var stateNum: ArrayList<Int>
    private lateinit var analysisAdapter: AnalysisAdapter
    private lateinit var subjectAdapter: SubjectAdapter
    private lateinit var stuList: ArrayList<String>
    private lateinit var popWnd: PopupWindow
    private lateinit var exportDialog: ExportTestPaperDialog
    private var shareFileLocalPath = ""
    private var showChart = false
    private val mViewModel: MarkViewModel by viewModel()

    override fun setLayoutID(): Int {
        return R.layout.activity_check_score
    }

    override fun providerVMClass(): Class<CheckScoreViewModel>? {
        return CheckScoreViewModel::class.java
    }

    override fun initView() {
        binding.presenter = this
        binding.vm = viewModel
        popWnd = PopupWindow(this)
        exportDialog = ExportTestPaperDialog(this)
        setId = intent.extras!!.getString("setId", "")
        paperId = intent.extras!!.getString("paperId", "")
        layer = intent.extras!!.getInt("layer")
        paperName = intent.extras!!.getString("paperName", "")
        viewModel.title.set(paperName + "的成绩")
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.analysis_tv -> {
//                viewModel.isStuAnalyze.set(true)
            }
            R.id.subject_tv -> {
//                viewModel.isStuAnalyze.set(false)
            }
            R.id.sbtn_back -> {
                finish()
            }
            R.id.tv_comment -> {
                AibkPaperEvaluationActivity.launch(this, paperId, setId)
            }
            R.id.output_tv -> {
                exportDialog.show()
                getExportTestPaperZipPath()
            }
        }
    }

    override fun initData() {
        loadingDialog.show()
        viewModel.getPaperAnalysis(
                CurrentUser.getUserID(),
                CurrentUser.getToken(),
                setId,
                paperId,
                CurrentUser.getSchoolID(),
                Ext.COURSE_CLASSID)
        state = ArrayList()
        stateNum = ArrayList()
        stuList = ArrayList()
        state.add("优秀")
        state.add("良好")
        state.add("合格")
        state.add("不合格")
        stateNum.add(0)
        stateNum.add(0)
        stateNum.add(0)
        stateNum.add(0)
    }

    //获取柱状图学生作答统计
    @RequiresApi(Build.VERSION_CODES.M)
    private fun getStuAnalysis(studentList: List<StuScore>) {
        studentList.forEach {
            when (it.Section) {
                "优秀" -> {

                    stateNum[0]++
                }
                "良好" -> {
                    stateNum[1]++
                }
                "合格" -> {
                    stateNum[2]++
                }
                "不合格" -> {
                    stateNum[3]++
                }
            }
        }

        val yMaxValue = 5 - (studentList.size % 5) + studentList.size
        if (!showChart) {
            emptyChart()
            return
        } else {
            binding.unitTv.visibility = View.VISIBLE
            binding.emptyIv.visibility = View.GONE
            binding.statisticalChart.visibility = View.VISIBLE
            binding.statisticalChart.showBarChart(state, stateNum, 4, 5, yMaxValue.toFloat(), true)
            binding.statisticalChart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener {
                override fun onNothingSelected() {}
                override fun onValueSelected(e: Entry?, h: Highlight?) {
                    popWnd.showAsDropDown(binding.statisticalChart, h!!.x.toInt(), h.y.toInt())
                }
            })
        }
    }

    private fun emptyChart() {
        binding.unitTv.visibility = View.INVISIBLE
        binding.emptyIv.visibility = View.VISIBLE
        binding.statisticalChart.visibility = View.INVISIBLE
    }

    private fun initAdapter(stuList: MutableList<StuScore>, subjectList: MutableList<TypeScoreRate>) {
        analysisAdapter = AnalysisAdapter(R.layout.item_analysis, stuList)
        binding.rvAnalysis.layoutManager = LinearLayoutManager(this)
        analysisAdapter.onItemClickListener = this
        binding.rvAnalysis.recycledViewPool.setMaxRecycledViews(0, 10)
        binding.rvAnalysis.adapter = analysisAdapter
        subjectAdapter = SubjectAdapter(
                layer,
                viewModel.paperAnalysisInfo.value!!.PaperID,
                this,
                lifecycle,
                R.layout.item_subject,
                subjectList
        )
        binding.rvSubject.layoutManager = LinearLayoutManager(this)
        binding.rvSubject.adapter = subjectAdapter
    }

    override fun onCancel(view: View?) {

    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
//        val intent = Intent(this, AibkPersonalAnalysisPaperAnswerSheetActivity::class.java)
//        intent.putExtra("stuId", viewModel.paperAnalysisInfo.value!!.StuScoreList[position].StuID)
//        intent.putExtra("stuName", viewModel.paperAnalysisInfo.value!!.StuScoreList[position].StuName)
//        intent.putExtra("paperId", viewModel.paperAnalysisInfo.value!!.PaperID)
//        intent.putExtra("layer", layer)
//        startActivity(intent)

        val stuId = viewModel.paperAnalysisInfo.value!!.StuScoreList[position].StuID
        val paperId = viewModel.paperAnalysisInfo.value!!.PaperID
        val paperName = viewModel.paperAnalysisInfo.value!!.PaperName
        val setName = viewModel.paperAnalysisInfo.value!!.SetName
        val setId = viewModel.paperAnalysisInfo.value!!.SetID
        AibkAnalysisAnswerSheetActivity.launch(this, stuId, paperId, paperName, setName, setId)
    }

    //导出分析
    private fun getExportTestPaperZipPath() {

        mViewModel.exportPaperScore(paperId, setId)
                .doOnSubscribe {

                }.bindLifeCycle(this)
                .subscribe({
                    checkPermission()
                    if (it.code == 1) {
                        val path = it.data
                        Thread(Runnable {
                            val zipLocalFilePath = ("Android/data/com.lancoo.znbkxx.teacher/" + CurrentUser.getUserID() + "/"
                                    + layer)
                            shareFileLocalPath = Environment.getExternalStorageDirectory().absolutePath + "/" + zipLocalFilePath + "/" + path.substring(path.lastIndexOf("/"))
                            if (File(shareFileLocalPath).exists()) {
                                exportDialog.dismiss()
                                ExportUtil.shareFile(this@CheckScoreActivity, shareFileLocalPath, applicationContext)
                            } else {
                                downLoadFile(path, zipLocalFilePath) //调用下载函数
                            }
                        }).start()
                    } else {
                        exportDialog.dismiss()
                        MyToast.showToast(it.message)
                    }

                }, {
                    exportDialog.dismiss()
                    MyToast.showToast(it.message)
                })

//        viewModel.getExportPaperScorePath(
//                CurrentUser.Token,
//                CurrentUser.SchoolID,
//                paperId,
//                Ext.COURSE_CLASSID,
//                Ext.GLOBAL_GRADE,
//                layer,
//                Ext.COURSE_CLASSNAME,
//                Ext.KEY,
//                CurrentUser.UserID,
//                object : CheckScoreViewModel.DataCallback {
//                    override fun onSuccess(path: String) {
//                        checkPermission()
//
//                        Thread(Runnable {
//                            val zipLocalFilePath = ("Android/data/com.lancoo.znbkxx.teacher/" + CurrentUser.UserID + "/"
//                                    + layer)
//                            shareFileLocalPath = Environment.getExternalStorageDirectory().absolutePath + "/" + zipLocalFilePath + "/" + path.substring(path.lastIndexOf("/"))
//                            if (File(shareFileLocalPath).exists()) {
//                                exportDialog.dismiss()
//                                ExportUtil.shareFile(this@CheckScoreActivity, shareFileLocalPath, applicationContext)
//                            } else {
//                                downLoadFile(path, zipLocalFilePath) //调用下载函数
//                            }
//                        }).start()
//                    }
//
//                    override fun onError(msg: String) {
//                        exportDialog.dismiss()
//                    }
//                }
//        )
    }

    private fun initPopupWindow() {
        val contentView = LayoutInflater.from(this).inflate(R.layout.stulist_pop_view, null)
        val rvStu = contentView.findViewById<RecyclerView>(R.id.rv_stu)
        rvStu.layoutManager = LinearLayoutManager(this)
        popWnd.contentView = contentView
        popWnd.width = ViewGroup.LayoutParams.WRAP_CONTENT
        popWnd.height = ViewGroup.LayoutParams.WRAP_CONTENT
    }

    private fun initPopData() {

    }

    //sd 卡权限申请
    private fun checkPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE), 100)
        }
    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 100) {

        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    @SuppressLint("SetTextI18n")
    override fun startObserve() {
        viewModel.mErrorMsg.observe(this, Observer {
            emptyChart()
            MyToast.showToast(it)
            loadingDialog.dismiss()
        })

        viewModel.paperAnalysisInfo.observe(this, Observer {
            loadingDialog.dismiss()
            viewModel.submitNum.set(it.SubmitCount.toString())
            viewModel.unSubmitNum.set(it.NoSubmitCount.toString())
            viewModel.finishNum.set(it.CompleteEvalCount.toString())
            viewModel.avgNum.set(it.AvgScore)
            viewModel.topNum.set(it.TopScore)
            viewModel.goodNum.set(it.BestRate)
            viewModel.passNum.set(it.PassRate)
            showChart = it.SubmitCount > 0
            getStuAnalysis(it.StuScoreList)
            initAdapter(it.StuScoreList, it.TypeScoreRateList)
        })
    }

    //下载文件
    private fun downLoadFile(urlLoadPath: String, saveDirPath: String): Boolean {
        var inputStream: InputStream? = null
        var fileOutputStream: FileOutputStream? = null
        var httpURLConnection: HttpURLConnection? = null
        if (Environment.MEDIA_MOUNTED != Environment.getExternalStorageState()) {
            return false
        }
        val pathSd = Environment.getExternalStorageDirectory() //获取 SD 卡路径
        val fileRealDirectory = File(pathSd.absolutePath + File.separator + saveDirPath)
        shareFileLocalPath = fileRealDirectory.toString() + "/" + urlLoadPath.substring(urlLoadPath.lastIndexOf("/"))
        if (!fileRealDirectory.exists()) { //如果目录 不存在 ，就创建
            fileRealDirectory.mkdirs()
        }
        val fileName = urlLoadPath.substring(urlLoadPath.lastIndexOf("/") + 1)
        val file = File(fileRealDirectory, fileName)
        if (!file.exists()) { //倘若没有这个文件
            try {
                file.createNewFile() //创建这个文件
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        try {
            val url = URL(urlLoadPath)
            httpURLConnection = url.openConnection() as HttpURLConnection
            httpURLConnection.connect()
            val code = httpURLConnection.responseCode
            if (code != 200) { //网络返回异常
                MyToast.showToast("网络异常，导出失败...")
                exportDialog.dismiss()
            }
            //根据响应获取文件大小
            val fileSize = httpURLConnection.contentLength
            inputStream = httpURLConnection.inputStream
            fileOutputStream = FileOutputStream(file)
            val b = ByteArray(1024)
            var tem = 0
            while (inputStream.read(b).also { tem = it } != -1) {
                fileOutputStream.write(b, 0, tem)
            }
            exportDialog.dismiss()
            ExportUtil.shareFile(this@CheckScoreActivity, shareFileLocalPath, applicationContext)
        } catch (e: MalformedURLException) {
            e.printStackTrace()
            return false
        } catch (e: IOException) {
            e.printStackTrace()
            return false
        } finally {
            try {
                inputStream?.close()
                fileOutputStream?.close()
                httpURLConnection?.disconnect()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return true
    }

}